#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   secon.sh
# Version:    1.0
# Date:       2013/12/17
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    03系统安全功能-01SELinux-03SELinux重要命令-03SELinux安全上下文标签相关命令-12secon
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/12/17
#             - secon
# ----------------------------------------------------------------------

##! @TODO: enforcing
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoSetup()
{
    trap DoCleanup EXIT INT 

    IsRoot
    EchoResult "root"

    CmdCheck getenforce genhomedircon

    # check selinux status is enforcing or permissive
    CheckSElinuxStatus
    EchoResult "check selinux status is enforcing or permissive"

    # set selinux enforcing
    SELINUX_STATUS=`getenforce | tr A-Z a-z`
    SetSElinux enforcing
    EchoResult "set selinux enforcing"

    # check sshd
    SERV=sshd
    StatusDaemon ${SERV}
    EchoResult "check ${SERV} start"

    # mkdir tmpdir
    TMPDIR=/tmp/selinux$$
    cmd="mkdir ${TMPDIR}"
    $cmd
    [ -d ${TMPDIR} ]
    EchoResult "$cmd"

    # prepare "secon -f /root" result 
    cat <<-EOF > ${TMPDIR}/secon.root
user: system_u
role: object_r
type: admin_home_t
sensitivity: s0
clearance: s0
mls-range: s0
EOF

    # prepare "secon -p pid" result
    cat <<-EOF > ${TMPDIR}/secon.pid
user: system_u
role: system_r
type: sshd_t
sensitivity: s0
clearance: s0:c0.c1023
mls-range: s0-s0:c0.c1023
EOF

}

##! @TODO: 
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function DoTest()
{
    secon -f /root > ${TMPDIR}/secon.root$$
    [ -f ${TMPDIR}/secon.root$$ ] 
    EchoResult "secon -f /root"

    # check result 
    diff ${TMPDIR}/secon.root ${TMPDIR}/secon.root$$
    EchoResult "check /root context"

    local PID_SSHD=`ps aux |grep  /usr/sbin/sshd | grep -v grep| awk '{print $2}'`
    secon -p ${PID_SSHD} > ${TMPDIR}/secon.pid$$
    [ -f ${TMPDIR}/secon.pid$$ ]
    EchoResult "secon -p ${PID_SSHD}"

    # check result
    diff ${TMPDIR}/secon.pid ${TMPDIR}/secon.pid$$
    EchoResult "check ${PID_SSHD} context"

}
##! @TODO: cleanup
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoCleanup()
{
    # restore selinux
    SetSElinux ${SELINUX_STATUS}
    EchoResult "restore selinux to ${SELINUX_STATUS}"

    # rm tmpdir
    [ -e ${TMPDIR} ] && rm -rf ${TMPDIR}
}

# include lib files

if [ -z "$SFROOT" ]
then
    echo "SFROOT is null, pls check"
    exit 1
fi

. ${SFROOT}/lib/Echo.sh
. ${SFROOT}/lib/Check.sh
. ${SFROOT}/lib/NetOps.sh
. ${SFROOT}/testcases/SELinux/lib/Selib.sh
. ${SFROOT}/testcases/SELinux/lib/UserOps.sh

export LANG=C

DoSetup
DoTest
EchoResult "testcase: selinux- secon"
echo ""
